﻿using SMS.Domain.Abstract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcPaging;
using AutoMapper;
using SMS.WebUI.Models;
using SMS.Domain.Entities;
using SMS.Domain.Concrete;

namespace SMS.WebUI.Controllers
{
    public class RetoController : Controller
    {
        public int PageSize = 2;
        private IRetoRepository repository;
        public RetoController(IRetoRepository retoRepository)
        {
            repository = retoRepository;
        }

        public ViewResult List(int page = 1, int? categoriaId = null, string descripcion = "")
        {

            //.Where(r => (categoriaId == null) ||(r.Categorias!=null && r.Categorias.Select(rc => rc.CategoriaId).Contains(categoriaId.GetValueOrDefault(-1))))
            return View

            (
                repository.Retos
                .Where(r => (categoriaId == null) || (r.Categorias.Count(rc => rc.CategoriaId == categoriaId) > 0))
                .Where(r => string.IsNullOrEmpty(descripcion) || r.Descripcion.Contains(descripcion))
                .OrderBy(r => r.RetoId)
                .ToPagedList(page - 1, PageSize)
            );

        }

        public ViewResult Details(int id)
        {
            return View(
                repository.Retos
                .FirstOrDefault(r=>r.RetoId==id)
                );
        }
        public ViewResult Create()
        {
            return View(new AltaOngDelModel());
        }

        [HttpPost]
        public ViewResult Create(AltaOngDelModel alta)
        {

            if (ModelState.IsValid)
            {
                Mapper.CreateMap<OngDelegacionModel, OngDelegacion>();
                Mapper.CreateMap<OngModel, Ong>();
                var modelDel = Mapper.Map<OngDelegacionModel, OngDelegacion>(alta.Delegacion);
                var modelOng = Mapper.Map<OngModel, Ong>(alta.Ong);
                var dbOng = new EFDbContext();
                modelOng.OngDelegaciones.Add(modelDel);
                dbOng.Onges.Add(modelOng);
                dbOng.SaveChanges();
                return null;
            }
            else
                return View(alta);
        }
    }
}
